﻿using AutoMapper;
using B.S.BasicData.API.Read.Application.Command.Role;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Read.Application.Handler.Role
{
    /// <summary>
    /// 根据角色Id获取用户信息请求命令处理类
    /// </summary>
    public class FanTianUserIdByRoleIdHandler:IRequestHandler<FanTianUserIdByRoleIdCommand,ApiResult<List<UserRoleDTO>>>
    {
        IBaseRepository<RoleModel> roleRep;
        IBaseRepository<UserRoleModel> userRoleRep;
        IBaseRepository<UserModel> userRep;
        IMapper mapper;

        public FanTianUserIdByRoleIdHandler(IBaseRepository<RoleModel> roleRep, IBaseRepository<UserRoleModel> userRoleRep,IMapper mapper, IBaseRepository<UserModel> userRep)
        {
            this.roleRep = roleRep;
            this.userRoleRep = userRoleRep;
            this.mapper = mapper;
            this.userRep = userRep;
        }

        public Task<ApiResult<List<UserRoleDTO>>> Handle(FanTianUserIdByRoleIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<UserRoleDTO>> res = new ApiResult<List<UserRoleDTO>>();

                var userids = userRoleRep.GetAll().Where(x => x.RoleId == request.roleid&&!x.IsDeleted);
                var model=mapper.Map<List<UserRoleDTO>>(userids);

                foreach (var item in model)
                {
                    item.UserId = userRep.GetAll().Where(x => x.Id ==item.UserId).Select(x=>x.Id).FirstOrDefault();
                    item.UserName = userRep.GetAll().Where(x => x.Id == item.UserId).Select(x => x.UserName).FirstOrDefault();
                    item.DepartmentId = userRep.GetAll().Where(x => x.Id == item.UserId).Select(x => x.DepartmentId).FirstOrDefault();
                }

                res.Msg = "根据角色Id获取用户信息";
                res.Code = ApiEnum.Success;
                res.Data = model;
                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
